package com.archive.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.archive.common.*;
import com.archive.dto.PageDTO;
import com.archive.entity.*;
import com.archive.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Janus
 * @since 2023-12-08
 */
@Api(tags = {"用户管理"})
@RestController
@RequestMapping({"user","home/user"})
public class UserController {
    private static  final Logger logger= LoggerFactory.getLogger(UserController.class);

    @Value("${com.jane.security.md5.key}")
    private String md5Key;

    @Autowired
    SysFileService fileService;

    @Autowired
    SysUserService userService;


    @Value("${com.jane.file.baseFilePath}")
    private String baseFilePath;

    @Autowired
    SysExpireService expireService;

    @Autowired
    SysDictValueService dictValueService;

    @Resource
    private SysFacultyService facultyService;
    @Resource
    private SysMajorService majorService;

    //根据ID获取用户信息
    @RequestMapping("info/{id}")
    public ResponseBean info(@PathVariable Long id){
        return ResultUtil.successData(userService.getById(id));
    }



    /**
     * 用户添加
     * @param user
     * @return
     */
    @ApiOperation(value = "用户添加，头像用formdata传输 key为file")
    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean addUser(SysUser user, MultipartFile file){
        return userService.addUser(user, file);
    }


    /**
     * 修改用户密码
     * @param id
     * @param password
     * @param oldPassword
     * @return
     */
    @ApiOperation(value = "修改用户密码")
    @RequestMapping(value = "updatePWd",method = RequestMethod.POST)
    @ResponseBody
    public  ResponseBean updatePWd(Long id,String oldPassword,String password,HttpSession session){
        SysUser user = userService.getById(id);
        String userPassword = user.getPassword();
        if(!MD5Util.md5Verify(oldPassword,md5Key,userPassword)){
            return ResultUtil.error("原始密码不正确！");
        }
        user.setPassword(MD5Util.md5(password,md5Key));
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        session.setAttribute("user",user);
        return ResultUtil.successData(user);
    }




    /**
     * 用户修改
     * @param user
     * @return
     */
    @ApiOperation(value = "用户修改")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean updateById(MultipartFile file, SysUser user,HttpSession session) {
        if (user == null) {
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        String mobile = user.getMobile();
        if(!StringUtils.isEmpty(mobile)&&!RegexUtil.checkMobile(mobile)){
            return ResultUtil.error("手机号不合法！");
        }

        if(user.getFacultyId()!=null){
            SysFaculty faculty = facultyService.getById(user.getFacultyId());
            user.setFacultyName(faculty.getName());
        }
        if(user.getMajorId()!=null){
            SysMajor major = majorService.getById(user.getMajorId());
            user.setMajorName(major.getName());
        }

        //处理密码
        String password = user.getPassword();
        if(!StringUtils.isEmpty(password)){
            user.setPassword(MD5Util.md5(password,md5Key));
        }else{
            user.setPassword(null);
        }
        if (file!=null&&!file.isEmpty()) {
            SysFile sysFile=new SysFile();
            sysFile.setObjectId(user.getId());
            sysFile.setCategoryCode(ComCodeEnum.category_code_user);
            SysFile saveFile=fileService.saveOrUpdateFile(sysFile,file);
            if(saveFile!=null&&!StringUtils.isEmpty(saveFile.getSaveName())){
                user.setImage(saveFile.getSaveName());
            }
        }

        user.setUpdateTime(LocalDateTime.now());
        boolean i = userService.updateById(user);
        return ResultUtil.successData(userService.getById(user.getId())) ;
    }


    /**
     * 分页列表查询
     * @param queryParam 查询参数
     * @return
     */
    @ApiOperation(value = "用户分页列表")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean getList(PageDTO pageDTO, SysUser queryParam , Integer isfull) {
        logger.debug("查询用户列表参数："+queryParam+",pageDTO:"+pageDTO);
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();

        if(isfull!=null&&isfull>0){
            float checkScore=5f;
            SysDictValue dictValue = dictValueService.getOne(new QueryWrapper<SysDictValue>().eq("dict_code", "quality_score"));
            if(dictValue!=null){
                checkScore=Float.parseFloat(dictValue.getDictValue());
            }
            //已修满
            queryWrapper.ge(isfull ==1,"score",checkScore);
//            未修满
            queryWrapper.le(isfull ==2,"score",checkScore);
        }
        queryWrapper.eq(queryParam.getId()!=null,"id",queryParam.getId());
        queryWrapper.eq(queryParam.getSex()!=null,"sex",queryParam.getSex());
        queryWrapper.eq(queryParam.getType()!=null,"type",queryParam.getType());
        queryWrapper.eq(queryParam.getState()!=null,"state",queryParam.getState());
        queryWrapper.like(!StringUtils.isEmpty(queryParam.getName()),"name",queryParam.getName());
        queryWrapper.like(!StringUtils.isEmpty(queryParam.getMobile()),"mobile",queryParam.getMobile());
        queryWrapper.ne("code","admin");//用户管理里面超级管理员admin除外
        queryWrapper.orderBy(true,pageDTO.getIsAsc().equals("asc"), ToolsUtils.camelToUnderline(pageDTO.getOrderByColumn()));
        IPage<SysUser> indexPage = new Page<>(pageDTO.getPageNum(),pageDTO.getPageSize());
        IPage<SysUser> listPage = userService.page(indexPage, queryWrapper);
        logger.debug("获取的用户列表："+listPage);
        //获取分页信息
        Map pageInfo = ToolsUtils.wrapperPageInfo(listPage);
        return ResultUtil.successData(pageInfo);
    }

    /**
     * 用户删除
     * @param idList
     * @return
     */
    @ApiOperation(value = "用户删除")
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean delete(@RequestParam("idList") List<Long> idList){
        if(idList==null||idList.isEmpty()){
            return ResultUtil.error("ID不合法！");
        }
        idList.forEach(e->userService.removeById(e));
        return ResultUtil.success();
    }

    @RequestMapping(value = "updateState",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean updateState(Long id,int state){
        SysUser sysUser = userService.getById(id);
        sysUser.setState(state);
        userService.updateById(sysUser);
        return ResultUtil.success();
    }


    /**
     * 后台用户登录
     * @param user
     * @param session
     * @return
     */
    @ApiOperation(notes = "用户登录，只需要code password",value = "")
    @RequestMapping("/checkLogin")
    @ResponseBody
    public ResponseBean checkLogin(SysUser user, HttpSession session) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("code",user.getCode());
        List<SysUser> list = userService.list(queryWrapper);
        //判断是否存在当前用户
        if (ToolsUtils.isEmpty(list)) {
            return new ResponseBean(false, CommonEnum.NO_USER_EXIST);
        }
        SysUser sysUser = list.get(0);
        if(sysUser.getState()!=1){
            return ResultUtil.error("用户已经被禁用，请联系管理员！");
        }
        //判断密码是否正确
        if (!MD5Util.md5Verify(user.getPassword(), this.md5Key, sysUser.getPassword())) {
            return new ResponseBean(false, CommonEnum.INVALID_PASSWORD);
        }

        //通过所有验证
        session.setAttribute("user", sysUser);
        session.setAttribute("type", sysUser.getType());

        SysExpire sysExpire=expireService.saveToken(list.get(0).getId());

        return ResultUtil.successData( sysExpire);
    }

    @RequestMapping("logout")
    public ResponseBean logout(Long userId){
        expireService.logout(userId);
        return ResultUtil.success();
    }

}
